<?php
/**
 * @package     Yjnic
 * @author      prettyyjnic <prettyyjnic@qq.com> 2015-12-27
 */

class Yjnic_ApiClient {

	private $_configs = array();
    private $_curl_url = '';
    private $_curl_params = array();

    public function __construct($configs) {
    	if (empty($configs)) {
    		throw new Yjnic_Exception("ApiClient configs can not be empty", 501);
    	}
    	if (!is_object(DI()->curl)) {
    		throw new Yjnic_Exception("ApiClient depends on curl", 502);	
    	}
    	$this->_configs = $configs;
    }

    public function get($service, $params=array()){
    	$url = $this->_configs['host'] . '?service=' . $service;
    	$this->_addSign($service, $params);
    	if (!empty($params)) {
    		$url .= '&'. http_build_query($params);
    	}
    	$timeout = isset($this->_configs['timeout']) ? $this->_configs['timeout'] : 3;
        $this->_curl_url = $url;
    	$curl_ret = DI()->curl->get($url, $timeout);
    	return $this->_dealRet($curl_ret);
    }

    public function post($service, $params=array()){
    	$url = $this->_configs['host'] . '?service=' . $service;
    	$this->_addSign($service, $params, $this->_configs);
    	$timeout = isset($this->_configs['timeout']) ? $this->_configs['timeout'] : 3;
    	$this->_curl_url = $url;
        $this->_curl_params = $params;
        $curl_ret = DI()->curl->post($url, $params, $timeout);        
    	return $this->_dealRet($curl_ret);
    }

    //验签
    private function _addSign($service, &$params){
    	if (is_subclass_of(DI()->filter, 'PhalApi_Filter')) {
    		DI()->filter->sign($service, $params, $this->_configs['sign_str']);
    	}
    }

    // 处理结果
    private function _dealRet($curl_ret){
        $this->_log($curl_ret);
    	$ret = json_decode($curl_ret, true);
    	if ($ret === false || empty($ret)) {
            return new Yjnic_ApiClientException('Internal Server Error', 500);
        }
        if ($ret['ret'] !== 200) {
            $this->_log($curl_ret, 'error');
        	return new Yjnic_ApiClientException($ret['msg'], $ret['ret']);
        }
        return $ret['data'];
    }

    private function _log($ret, $type='info'){
        if (isset($this->_configs['log']) && $this->_configs['log'] == true ){
            $msg = '[request url :'.$this->_curl_url.'][request params :'.json_encode($this->_curl_params).']';
            DI()->logger->log( $type, $msg, $ret);
        }
        $this->_reset();
    }

    private function _reset(){
        $this->_curl_url = '';
        $this->_curl_params = array();
    }
}


/**
 * Exception类 Yjnic_Exception
 *
 * @author prettyyjnic <prettyyjnic@qq.com> 20151027
 */
class Yjnic_ApiClientException extends Exception {

	public function __construct($message, $code=500){
		parent::__construct(
			'Yjnic ApiClient exception:' . $message, $code
		);
	}
}